package cn.jasonone.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jasonone.bean.Book;
import cn.jasonone.service.BookService;
import cn.jasonone.service.impl.BookServiceImpl;
import cn.jasonone.vo.PageInfo;

public class BookServlet extends HttpServlet {
	private BookService bookService = new BookServiceImpl();
	
	private Book parseBook(HttpServletRequest req) {
		Book book = new Book();
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String price = req.getParameter("price");
		String publisher = req.getParameter("publisher");
		String inventory = req.getParameter("inventory");
		String status = req.getParameter("status");
		book.setName(name);
		book.setPublisher(publisher);
		if (id != null && id.matches("\\d+")) {
			book.setId(Integer.valueOf(id));
		}
		if (inventory != null && inventory.matches("\\d+")) {
			book.setInventory(Integer.valueOf(inventory));
		}
		if (status != null && status.matches("\\d+")) {
			book.setStatus(Integer.valueOf(status));
		}
		if (price != null && price.matches("\\d+\\.?\\d*")) {
			book.setPrice(Double.valueOf(price));
		}
		return book;
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json");
		String page = req.getParameter("page");
		String pageSize = req.getParameter("pageSize");
		if(page == null || !page.matches("\\d+")) {
			page = "1";
		}
		if(pageSize == null || !pageSize.matches("\\d+")) {
			pageSize = "10";
		}
		
		PageInfo<Book> pageInfo = bookService.findAll(Integer.valueOf(page),Integer.valueOf(pageSize),this.parseBook(req));
		// 
		resp.getWriter().print(pageInfo); // resp.getWriter().print(pageInfo.toString());
	
	
	}
	
}
